package com.farewell.blog.controller;

import com.farewell.blog.pojo.Blog;
import com.farewell.blog.pojo.Comment;
import com.farewell.blog.service.BlogService;
import com.farewell.blog.service.CommentService;
import com.farewell.blog.utils.MarkdownUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Farewell
 * @date 2021/2/10
 */
@Controller
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    private ReentrantLock lock = new ReentrantLock();

    @GetMapping("/{id}")
    public String getBlogDetail(@PathVariable("id") Long id, Model model) {
        Blog blog = blogService.getBlogById(id);
        if (blog != null) {
            model.addAttribute("blog", blog);
            lock.lock();
            try {
                blog.setViews(blog.getViews() + 1);
                blogService.updateViews(blog);
                String content = blog.getContent();
                blog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        return "blog";
    }
}
